<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Service\PlayletService;
use App\Service\UserService;
use App\Service\CommService;
use App\Service\WxBizDataCrypt;

#[AutoController]
class UserController extends BaseController
{
    #[Inject]
    private PlayletService $playletService;
    #[Inject]
    private UserService $userService;
    #[Inject]
    private CommService $commService;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        return $response->raw('Hello!');
    }
    public function applet_info(RequestInterface $request, ResponseInterface $response) {
        $applet_id =  $this->get_applet_id();
        $res = $this->userService->get_applet_info($applet_id);
        $data['ad_unit_id'] = $res['ad_unit_id']?? 'nd4zj8c7fdnb0qones';
        $data['applet_id'] = $applet_id;
        $data['videopage'] = $res['videopage']??1;
        $data['square'] = $res['square']??2;
        $data['showInterval'] = $res['showInterval']??false;
        return $this->resultResponse(["data"=>$data]);
    }

    public function error_info(RequestInterface $request,ResponseInterface $response){
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        $error_info = $request->input('error_info', '');
        $errorcode = $request->input('errorcode', '0');
        if (empty($error_info) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $this->userService->error_info($applet_id,$error_info,$xc_open_id,$errorcode);
        return $this->resultResponse(["data"=>[]]);
    }

    public function info(RequestInterface $request,ResponseInterface $response){
        var_dump('调用uses/info');
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        if (empty($xc_open_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = $open_id_info['id'];
        $user_info_rec = $this->userService->user_info($applet_id,$user_id);
        $user_info = $this->get_user_info_rel($user_info_rec);
        $operation_mode = $this->userService->get_operation_mode($user_info);
        $user_info['operation_mode'] = $operation_mode ?? '1';
        unset($user_info_rec);
        return $this->resultResponse(["data"=>$user_info]);
    }

    public function data_decrypt(RequestInterface $request,ResponseInterface $response){
        print_r($request->all());
        $data = [];
        $appid = "wx8fb5d0128e0fff5c";
        $encryptedData = $request->input("encryptedData","");
        $sessionKey = $request->input("sessionKey","");
        $iv = $request->input("iv","");
        if (empty($encryptedData) or empty($sessionKey) or empty($iv)){
            return [
                "errcode"=>222222,
                "message"=>"参数错误",
                "content"=>"",
            ];
        }else{
            $pc = new WxBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );
            if ($data){
                $rec_data = json_decode($data);
            }else{
                $rec_data = [
                    "stepInfoList"=>[
                        [
                            "timestamp"=>time(),
                            "step"=>0,
                        ]

                    ]
                ];
            }
            echo "errCode: ".$errCode.PHP_EOL;
            $rec_data = [
                "errcode"=>$errCode,
                "content"=>$rec_data,
            ];
//            print_r($rec_data);
            return $rec_data;
        }


    }
    public function ios_payment(RequestInterface $request,ResponseInterface $response) {
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input("xc_open_id","");
        if (empty($xc_open_id) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $res = $this->userService->ios_payment($applet_id,$xc_open_id);
        if($res == true) {
            $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
            $user_id = $open_id_info['id'];
            $user_info_rec = $this->userService->user_info($applet_id,$user_id);
            $user_info = $this->get_user_info_rel($user_info_rec);
            unset($user_info_rec);
            return $this->resultResponse(["data"=>$user_info]);
        }
        return $this->resultResponse(["code"=>20001]);
    }
    public function get_openid(RequestInterface $request,ResponseInterface $response){
        $applet_id = $this->get_applet_id();
        $login_code = $request->input("login_code","");
        $spread_id = $request->input('spread_id', '0');
        $type = $request->input('type', '1');
        $all = $request->all();
        $login_code = $request->input("login_code","");
        $clue_token= $request->input("clue_token","");
        $promotion_id = $request->input("promotion_id",0);
        $promotionid = $request->input("promotionid",0);
        $click_id = $request->input("click_id",0);
        $platformType = $request->input('platform_type', '1');
        $login_data = $this->userService->get_dy_openid($applet_id,$login_code,0);
        $applet_info = $this->userService->get_user_applet_info($applet_id);
        $user_info = [];
        if (!empty($login_data["openid"])){
            $rec_data["applet_id"] = $applet_id;
            $rec_data["xc_open_id"] = $login_data["openid"];
            $rec_data["ip"] = $this->get_ip();
            $rec_data["ua"] = $this->get_user_ua();
            $rec_data["spread_id"] = $spread_id;
            if($promotion_id){
                $rec_data["ad_id"] = $promotion_id;
            }
            if($clue_token){
                $rec_data["clue_token"] = $clue_token;
            }
            if($click_id){
                $rec_data["click_id"] = $click_id;
            }
            $rec_data["all"] = json_encode($all);

                echo "get_openid-get_openid".PHP_EOL;
                # 查询用户注册
                $rec = $this->userService->get_xc_open_id_info($rec_data["applet_id"],$rec_data["xc_open_id"]);
//                print_r($rec);
                echo "查询用户基本信息".PHP_EOL;
                if (empty($rec)){
                    $userid = $this->userService->addUser($rec_data);
                    co(function () use ($rec_data,$userid) {
                        $this->userService->addRefluxLog([
                            'dyeing_time'=>date('Y-m-d H:i:s',time()),
                            'create_at'=>date('Y-m-d H:i:s',time()),
                            'spread_id'=>$rec_data["spread_id"],
                            'applet_id'=>$rec_data['applet_id'],
                            'user_id'=>$userid,
                            'ad_id'=>isset($rec_data['ad_id']) ? $rec_data['ad_id']:0,
                            'click_id'=>isset($rec_data['click_id']) ? $rec_data['click_id']:0,
                            'clue_token'=>isset($rec_data['clue_token']) ? $rec_data['clue_token']:0
                        ]);
                    });

                }
                else {
                    #判断回流
                    if(isset($rec_data["spread_id"]) && $rec_data["spread_id"] != 0 && $rec['spread_id'] != $rec_data["spread_id"]) {
                        #获取订单
                        $user_xc_open_id = $rec_data['xc_open_id'];
                        $user_id = $rec['id'];
                        $last_order = $this->userService->get_last_order($applet_id,$user_id,$rec["spread_id"]);
                        #判断是否48小时内
                        if($last_order == '' || strtotime($last_order['pay_time'])+60*60*24*2 < time()) {
                            $update_data = [];
                            $update_data['dyeing_time'] = date('Y-m-d H:i:s',time());
                            $update_data['spread_id'] = $rec_data["spread_id"];
                            $update_data['all'] = $rec_data["all"];
                            co(function () use ($rec_data,$user_id) {
                                $this->userService->addRefluxLog([
                                    'dyeing_time'=>date('Y-m-d H:i:s',time()),
                                    'create_at'=>date('Y-m-d H:i:s',time()),
                                    'spread_id'=>$rec_data["spread_id"],
                                    'applet_id'=>$rec_data['applet_id'],
                                    'ad_id'=>isset($rec_data['ad_id']) ? $rec_data['ad_id']:0,
                                    'click_id'=>isset($rec_data['click_id']) ? $rec_data['click_id']:0,
                                    'clue_token'=>isset($rec_data['clue_token']) ? $rec_data['clue_token']:0,
                                    'user_id'=>$user_id
                                ]);
                            });
                            if(isset($rec_data['ad_id'])) {
                                $update_data['ad_id'] = $rec_data['ad_id'];
                            }
                            if(isset($rec_data['clue_token']) ) {
                                $update_data['clue_token'] = $rec_data['clue_token'];
                            }
                            if(isset($rec_data['click_id']) )
                            {
                                $update_data['click_id'] = $rec_data['click_id'];
                            }
                            $this->userService->updateUser($rec_data["applet_id"],$user_xc_open_id,$update_data);
                        }
                    }
                }
                #回流保留
            $user_info["openid"] =  $login_data["openid"];
            $user_info["session_key"] =  $login_data["session_key"];
//            if($type == 2) {
//                $user_info['unionid'] = $login_data['unionid'];
//            }
            $user_info["coin_name"] =  $applet_info["coin_name"];
        }
        if (empty($user_info)){
            return $this->resultResponse(["code"=>"20002"]);
        }else{
            #记录登陆日志
            return $this->resultResponse(["data"=>$user_info]);
        }
    }
//    public function get_openid(RequestInterface $request,ResponseInterface $response){
//        $applet_id = $this->get_applet_id();
//        $all = $request->all();
//        $login_code = $request->input("login_code","");
//        $clue_token= $request->input("clue_token","");
//        $promotion_id = $request->input("promotion_id",0);
//        $click_id = $request->input("click_id",0);
////        $optionsObj = $request->input("optionsObj","");
//        $spread_id = $request->input('spread_id', '0');
//        $spread_id = intval($spread_id);
//        $platformType = $request->input('platform_type', '');
//        $login_data = $this->userService->get_wx_openid($applet_id,$login_code,$platformType,0);
//        $applet_info = $this->userService->get_user_applet_info($applet_id);
//        $user_info = [];
//        if (!empty($login_data["openid"])){
//            $rec_data["applet_id"] = $applet_id;
//            $rec_data["xc_open_id"] = $login_data["openid"];
//            $rec_data["unionid"] = $login_data["unionid"];
//            $rec_data["ip"] = $this->get_ip();
//            $rec_data["ua"] = $this->get_user_ua();
//            $rec_data["spread_id"] = $spread_id;
//            if($promotion_id){
//                $rec_data["ad_id"] = $promotion_id;
//            }
//            if($clue_token){
//                $rec_data["clue_token"] = $clue_token;
//            }
//            if($click_id){
//                $rec_data["click_id"] = $click_id;
//            }
//            $rec_data["all"] = $all;
//
//            co(function () use ($rec_data) {
//                echo "get_openid-get_openid".PHP_EOL;
//                # 查询用户注册
//                $rec = $this->userService->get_xc_open_id_info($rec_data["applet_id"],$rec_data["xc_open_id"]);
////                print_r($rec);
//                echo "查询用户基本信息".PHP_EOL;
//                if (empty($rec)){
//                    $this->userService->addUser($rec_data);
//                }
//                else {
//                    #判断回流
//                    if(isset($rec_data["spread_id"]) && $rec_data["spread_id"] != 0) {
//                        #获取订单
//                        $user_xc_open_id = $rec_data['xc_open_id'];
//                        $user_id = $rec['id'];
//                        $last_order = $this->userService->get_last_order($user_id,$user_id);
//                        #判断是否48小时内
//                        if(empty($last_order) || strtotime($last_order['pay_time'])+60*60*24*2 >time()) {
//                            $update_data = [];
//                            $update_data['dyeing_time'] = date('Y-m-d H:i:s',time());
//                            $update_data['spread_id'] = $rec_data["spread_id"];
//                            $update_data['all'] = json_encode($rec_data["all"]);
//
//                            if(isset($rec_data['ad_id'])) {
//                                $update_data['ad_id'] = $rec_data['ad_id'];
//                            }
//                            if(isset($rec_data['clue_token']) ) {
//                                $update_data['clue_token'] = $rec_data['clue_token'];
//                            }
//                            if(isset($rec_data['click_id']) )
//                            {
//                                $update_data['click_id'] = $rec_data['click_id'];
//                            }
//                            $this->userService->updateUser($rec_data['applet_id'],$user_xc_open_id,$update_data);
//                        }
//                    }
//                }
//                #回流保留
//            });
//            $user_info["openid"] =  $login_data["openid"];
//            $user_info["session_key"] =  $login_data["session_key"];
////            if($type == 2) {
////                $user_info['unionid'] = $login_data['unionid'];
////            }
//            $user_info["coin_name"] =  $applet_info["coin_name"];
//        }
//        if (empty($user_info)){
//            return $this->resultResponse(["code"=>"20002"]);
//        }else{
//            #记录登陆日志
//            return $this->resultResponse(["data"=>$user_info]);
//        }
//    }
    public function likes_history(RequestInterface $request,ResponseInterface $response){
        # 点赞历史
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        $page = $request->input('page', '1');
        echo "用户信息".print_r($request->all()).PHP_EOL;
        if (empty($xc_open_id) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = $open_id_info['id'];
        $list = $this->playletService->get_user_likes_playlet($applet_id,$user_id,$page);
        return $this->resultResponse(["data"=>$list]);
    }

    public function recharge_log(RequestInterface $request,ResponseInterface $response){
        # 充值记录
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        $page = $request->input('page', '1');
        if (empty($xc_open_id) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = $open_id_info['id'];
        $list = $this->userService->recharge_log($applet_id,$user_id,$page);
        return $this->resultResponse(["data"=>$list]);
    }


    public function chasing_playlet(RequestInterface $request,ResponseInterface $response){
        # 追剧
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        $playlet_ids = $request->input('playlet_ids', '');
        $page = $request->input('page', '1');
        if (empty($xc_open_id) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = $open_id_info['id'];
        $list = $this->playletService->chasing_playlet($applet_id,$user_id,$page,$playlet_ids);
        return $this->resultResponse(["data"=>$list]);
    }

    public function playlet_history(RequestInterface $request,ResponseInterface $response){
        # 观看历史
        $applet_id = $this->get_applet_id();
        $xc_open_id = $request->input('xc_open_id', '');
        $page = $request->input('page', '1');
        if (empty($xc_open_id) or empty($applet_id)){
            return $this->resultResponse(["code"=>20001]);
        }
        $open_id_info = $this->userService->get_xc_open_id_info($applet_id,$xc_open_id);
        $user_id = $open_id_info['id'];
        $list = $this->playletService->playlet_history($applet_id,$user_id,$page);
        return $this->resultResponse(["data"=>$list]);
    }
}
